###Do Partisan Types Stop at the Water's Edge? 
#Partisan Types 0.R
#Josh Kertzer
#Last modified: February 13, 2020

### Note: this file loads the data and generates the variables necessary to produce the subsequent analysis; load this file first!

### All of the following analyses were carried out using R version 3.5.2 on a 3 GHz Intel Xeon W iMac Pro running macOS Mojave 10.14.6, and replicated using R version 3.5.2 on a 2 GHz Intel Core i7 Macbook Pro running macOS Mojave 10.14.5.

## Load dataframes and libraries
library(here) #Use to set working directory
library(haven)
library(ggplot2)
library(reshape2)
library(stargazer)
library(lme4)
library(ggrepel)
library(ggtern)
library(ordinal)
library(mgcv)

dat1 <- get(load("Study 1 Data.RData"))
dat2 <- get(load("Study 2 Data.RData"))

##Functions for cleaning

#Recode our variables
recode <- function(variable, reverse=FALSE, maxVal, minVal, binarize=FALSE, x=NA, x2){
  if (is.factor(variable)){variable <- as.numeric(variable)}
  if (missing(maxVal)){maxVal <- max(variable, na.rm=TRUE)}
  if (missing(minVal)){minVal <- min(variable, na.rm=TRUE)}
  variable[variable > maxVal] <- NA
  variable[variable < minVal] <- NA
  if (reverse){
    temp <- variable
    for (j in 1:maxVal){
      temp[which(variable==j)] <- maxVal-j+1
    }
    return(temp)
  }
  if (binarize){
    if (is.na(x)){stop("Specify the value to dichotomize on")}
    temp <- variable
    if (missing(x2)){
      i <- which(variable == x)
      k <- which(variable < x | variable > x)
    }
    else{
      i <- which(variable >= x & variable <= x2)
      k <- which(variable < x | variable > x2)
    }
    temp[i] <- 1
    temp[k] <- 0
    return(temp)
  }
  return(variable)
}

#Rescale from 0-1
rescale <- function(x){
	return((x-min(x,na.rm=TRUE))/(max(x-min(x,na.rm=TRUE),na.rm=TRUE)))
}

#Convert verbal likert to numeric
likert <- function(x, points=7){
    if (points!=7 & points!=5){stop("Currently requires a 5 or 7 point scale")}
	y <- rep(NA, length(x))
	if (points==7){
	y[which(x=="Strongly agree")] <- 7
	y[which(x=="Agree")] <- 6
	y[which(x=="Slightly agree")] <- 5
	y[which(x=="Somewhat agree")] <- 5
	y[which(x=="Neither agree nor disagree")] <- 4
	y[which(x=="Somewhat disagree")] <- 3
	y[which(x=="Disagree")] <- 2
	y[which(x=="Strongly disagree")] <- 1
	}
	else if (points==5){
	y[which(x=="Strongly agree")] <- 5
	y[which(x=="Agree" | x=="Somewhat agree")] <- 4
	y[which(x=="Neither agree nor disagree")] <- 3
	y[which(x=="Disagree" | x=="Somewhat disagree")] <- 2
	y[which(x=="Strongly disagree")] <- 1	
	}
	return(y)
}

###Clean study 1

#Education
dat1$educ <- as.numeric(dat1$Q32)
dat1$educ_1 <- recode(dat1$educ, binarize=TRUE, x=1, x2=2) #High school or less
dat1$educ_2 <- recode(dat1$educ, binarize=TRUE, x=3) #Some college
dat1$educ_3 <- recode(dat1$educ, binarize=TRUE, x=4, x2=5) #College/University
dat1$educ_4 <- recode(dat1$educ, binarize=TRUE, x=6, x2=8) #Post-grad
#Continuous education measure
dat1$educ1 <- rescale(dat1$educ_1*1 + dat1$educ_2*2 + dat1$educ_3*3 + dat1$educ_4*4)

#PartyID: (scaled towards strong Republican)
dat1$pid <- ifelse(dat1$Q33==2 & dat1$Q72==1,1,ifelse(dat1$Q33==2 & dat1$Q72 ==2,2,ifelse(dat1$Q33==3 & dat1$Q73==2,3,ifelse(dat1$Q33==3 & dat1$Q73==3,4,ifelse(dat1$Q33==3 & dat1$Q73==1,5, ifelse(dat1$Q33==1 & dat1$Q71==2,6, ifelse(dat1$Q33==1 & dat1$Q71==1,7,NA)))))))
dat1$pid1 <- rescale(dat1$pid)

dat1$pid3 <- NA
dat1$pid3[which(dat1$pid<=3)] <- 1 #Include leaners as Dem
dat1$pid3[which(dat1$pid==4)] <- 2
dat1$pid3[which(dat1$pid>=5)] <- 3 #Include leaners as Rep

#Ideology: (scaled towards extremely conservative)
dat1$ideo <- recode(as.numeric(dat1$Q34), reverse=TRUE, maxVal=7)
dat1$ideo1 <- rescale(dat1$ideo)

#Fix income variable (it was categorical, now it's numeric, but the numbers should correspond with increases in income)
temp <- rep(NA, length(dat1$income))
temp[dat1$income==10] <- 1 #< 20K
temp[dat1$income==3] <- 2 #20-30K
temp[dat1$income==4] <- 3 #30-40K
temp[dat1$income==5] <- 4 #40-50K
temp[dat1$income==6] <- 5 #50-60K
temp[dat1$income==7] <- 6 #60-75K
temp[dat1$income==8] <- 7 #75-100K
temp[dat1$income==1] <- 8 #100K-150K
temp[dat1$income==2] <- 9 #>150K
temp[dat1$income==9] <- NA #DK
dat1$income <- temp

#Age
dat1$age_1 <- recode(dat1$age, binarize=TRUE, x=18, x2=24)
dat1$age_2 <- recode(dat1$age, binarize=TRUE, x=25, x2=44)
dat1$age_3 <- recode(dat1$age, binarize=TRUE, x=45, x2=64)
dat1$age_4 <- recode(dat1$age, binarize=TRUE, x=65, x2=95)

#Political interest
dat1$polInterest <- as.numeric(recode(dat1$Q35, reverse=TRUE, maxVal=4))
dat1$polInterest1 <- rescale(dat1$polInterest)

#Foreign policy interest
dat1$fpInterest <- as.numeric(recode(dat1$Q36, reverse=TRUE, maxVal=4))

#Define treatments:
#Approach: 0 control, 1 unilateral / multilateral
#stopPiracy: 0 control, 1 unilateral, 2 multilateral
dat1$stopPiracy <- ifelse(dat1$multi1=="", 0,ifelse(dat1$multi1=="The US would seek to stop piracy by deploying US military forces on their own without seeking military assistance from other countries or approval from the United Nations.",1,ifelse(dat1$multi1=="The US would seek to stop piracy by deploying US military forces alongside military personnel from many other countries by working through the United Nations.",2,NA)))

#enviroSanction: 0 control, 1 unilateral, 2 multilateral
dat1$enviroSanction <- ifelse(dat1$multi2=="", 0,ifelse(dat1$multi2=="The US would implement the sanctions by acting alone without seeking approval from the United Nations.",1,ifelse(dat1$multi2=="The US would implement the sanctions by cooperating with other countries and seeking backing from the United Nations.",2,NA)))

#troopsOil: 0 control, 1 unilateral, 2 multilateral
dat1$troopsOil <- ifelse(dat1$multi3=="", 0,ifelse(dat1$multi3=="The US would do so by deploying US ground troops on their own without seeking military assistance from other countries or backing from the United Nations.",1,ifelse(dat1$multi3=="The US would do so by deploying US ground troops alongside the troops provided by many other countries by working through the United Nations.",2,NA)))

#troopsCiv: 0 control, 1 unilateral, 2 multilateral
dat1$troopsCiv <- ifelse(dat1$multi4=="", 0,ifelse(dat1$multi4=="The US would do so by deploying US ground troops on their own without seeking military assistance from other countries or backing from the United Nations.",1,ifelse(dat1$multi4=="The US would do so by deploying US ground troops alongside the troops provided by many other countries by working through the United Nations.",2,NA)))

#freeTrade: 0 protectionist, 1 free trade
dat1$freeTrade <- ifelse(dat1$trade=="Decreasing limits on imports of foreign-made products, and signing more free trade agreements like NAFTA.",1,ifelse(dat1$trade=="Increasing limits on imports of foreign-made products, and refraining from signing more free trade agreements like NAFTA.",0,NA))

#proEnviro: 0 pro-drilling, 1 anti-drilling
dat1$proEnviro <- ifelse(dat1$enviro=="Decreasing offshore drilling for oil and gas in U.S. coastal areas and increasing restrictions on drilling on public lands in order to protect the environment.",1,ifelse(dat1$enviro=="Increasing offshore drilling for oil and gas in U.S. coastal areas and decreasing restrictions on drilling on public lands in order to increase energy production.",0,NA))

#interventionist: 0 less active FP, 1 more active FP
dat1$interventionist <- ifelse(dat1$intervene=="Encouraging the US to play an active role in solving problems around the world.",1,ifelse(dat1$intervene=="Discouraging the US from playing an active role in solving problems around the world.",0,NA))

#armsControl: 0 oppose deproliferation, 1 support deproliferation
dat1$armsControl <- ifelse(dat1$hawk1=="Opposing an arms control treaty that would reduce both US and Russian nuclear arsenals.",0,ifelse(dat1$hawk1=="Supporting an arms control treaty that would reduce both US and Russian nuclear arsenals.",1,NA))

#milSpend: 0 decrease, 1 increase
dat1$milSpend <- ifelse(dat1$hawk2=="Decreasing military spending to allow the US to better solve international problems.",0,ifelse(dat1$hawk2=="Increasing military spending to allow the US to better solve international problems.",1,NA))

#gunControl: 0 anti, 1 pro
dat1$gunControl <- ifelse(dat1$guns=="Passing a law lowering restrictions on the sale of firearms.",0,ifelse(dat1$guns=="Passing a law making the sale of firearms more strict than they are today.",1,NA))

#taxHike: 0 anti, 1 pro
dat1$taxHike <- ifelse(dat1$tax=="Passing a new law that would lower taxes on households earning $1 million a year or more.",0,ifelse(dat1$tax=="Passing a new law that would raise taxes on households earning $1 million a year or more.",1,NA))

#abortions: 0 anti-abortion, 1 pro-choice
dat1$abortions <- ifelse(dat1$abortion=="Placing stricter limits on abortions than there are now.",0,ifelse(dat1$abortion=="Allowing abortions to be generally available to those who want it.",1,NA))

#Convert policy series to numeric
loc.a <- which(colnames(dat1)=="Q4")
loc.b <- which(colnames(dat1)=="Q15")
for (i in loc.a:loc.b){
	dat1[,i] <- as.numeric(dat1[,i])
}

#Convert stereotype series to numeric
loc.a <- which(colnames(dat1)=="Q17")
loc.b <- which(colnames(dat1)=="Q28")
for (i in loc.a:loc.b){
	dat1[,i] <- as.numeric(dat1[,i])
}

### Clean study 2

## Age
dat2$age <- as.numeric(dat2$Q3.3)
dat2$age_1 <- recode(dat2$age, binarize=TRUE, x=18, x2=24)
dat2$age_2 <- recode(dat2$age, binarize=TRUE, x=25, x2=44)
dat2$age_3 <- recode(dat2$age, binarize=TRUE, x=45, x2=64)
dat2$age_4 <- recode(dat2$age, binarize=TRUE, x=65, x2=105)

## Education
dat2$educ_1 <- dat2$educ_2 <- dat2$educ_3 <- dat2$educ_4 <- 0
dat2$educ_1[which(dat2$Q3.4=="Less than high school" | dat2$Q3.4=="High school or GED")] <- 1
dat2$educ_2[which(dat2$Q3.4=="Some college")] <- 1
dat2$educ_3[which(dat2$Q3.4=="2-year college degree" | dat2$Q3.4=="4-year college degree")] <- 1
dat2$educ_4[which(dat2$Q3.4=="Master's degree" | dat2$Q3.4==
"Doctoral degree" | dat2$Q3.4=="Professional degree (e.g. JD or MD)")] <- 1
#Continuous education measure
dat2$educ1 <- rescale(dat2$educ_1*1 + dat2$educ_2*2 + dat2$educ_3*3 + dat2$educ_4*4)

## Race
dat2$white <- recode(as.factor(dat2$Q3.5),binarize=TRUE,x=6)

## Party ID
dat2$pid <- NA
dat2$pid[which(dat2$Q3.6=="Strong Democrat")] <- 1
dat2$pid[which(dat2$Q3.6=="Democrat")] <- 2
dat2$pid[which(dat2$Q3.6=="Independent but lean Democrat")] <- 3
dat2$pid[which(dat2$Q3.6=="Independent")] <- 4
dat2$pid[which(dat2$Q3.6=="Independent but lean Republican")] <- 5
dat2$pid[which(dat2$Q3.6=="Republican")] <- 6
dat2$pid[which(dat2$Q3.6=="Strong Republican")] <- 7
dat2$pid1 <- rescale(dat2$pid)

dat2$pid3 <- NA
dat2$pid3[which(dat2$pid<=3)] <- 1 #Include leaners as Dem
dat2$pid3[which(dat2$pid==4)] <- 2
dat2$pid3[which(dat2$pid>=5)] <- 3 #Include leaners as Rep

##Ideology
dat2$ideo <- NA
dat2$ideo[which(dat2$Q3.7=="Extremely liberal")] <- 1
dat2$ideo[which(dat2$Q3.7=="Liberal")] <- 2
dat2$ideo[which(dat2$Q3.7=="Slightly liberal")] <- 3
dat2$ideo[which(dat2$Q3.7=="Moderate")] <- 4
dat2$ideo[which(dat2$Q3.7=="Slightly conservative")] <- 5
dat2$ideo[which(dat2$Q3.7=="Conservative")] <- 6
dat2$ideo[which(dat2$Q3.7=="Extremely conservative")] <- 7
dat2$ideo1 <- rescale(dat2$ideo)

##Political interest
dat2$attention <- NA
dat2$attention[which(dat2$Q3.8=="None at all")] <- 1
dat2$attention[which(dat2$Q3.8=="A little")] <- 2
dat2$attention[which(dat2$Q3.8=="A moderate amount")] <- 3
dat2$attention[which(dat2$Q3.8=="A lot")] <- 4
dat2$attention[which(dat2$Q3.8=="A great deal")] <- 5

dat2$interest <- NA
dat2$interest[which(dat2$Q3.9=="Not interested at all")] <- 1
dat2$interest[which(dat2$Q3.9=="Slightly interested")] <- 2
dat2$interest[which(dat2$Q3.9=="Moderately interested")] <- 3
dat2$interest[which(dat2$Q3.9=="Very interested")] <- 4
dat2$interest[which(dat2$Q3.9=="Extremely interested")] <- 5

dat2$polInterest <- apply(with(dat2,cbind(attention,interest)),1,mean,na.rm=TRUE)
dat2$polInterest1 <- rescale(dat2$polInterest)

##### Treatments 

#troopsOil: 0 control, 1 unilateral, 2 multilateral
dat2$troopsOil <- ifelse(dat2$multi3=="", 0,ifelse(dat2$multi3=="The US would do so by deploying US ground troops on their own without seeking military assistance from other countries or backing from the United Nations.",1,ifelse(dat2$multi3=="The US would do so by deploying US ground troops alongside the troops provided by many other countries by working through the United Nations.",2,NA)))

#freeTrade: 0 protectionist, 1 free trade
dat2$freeTrade <- ifelse(dat2$trade=="Decreasing limits on imports of foreign-made products, and signing more free trade agreements like NAFTA.",1,ifelse(dat2$trade=="Increasing limits on imports of foreign-made products, and refraining from signing more free trade agreements like NAFTA.",0,NA))

#proEnviro: 0 pro-drilling, 1 anti-drilling
dat2$proEnviro <- ifelse(dat2$enviro=="Decreasing offshore drilling for oil and gas in U.S. coastal areas and increasing restrictions on drilling on public lands in order to protect the environment.",1,ifelse(dat2$enviro=="Increasing offshore drilling for oil and gas in U.S. coastal areas and decreasing restrictions on drilling on public lands in order to increase energy production.",0,NA))

#interventionist: 0 less active FP, 1 more active FP
dat2$interventionist <- ifelse(dat2$intervene=="Encouraging the US to play an active role in solving problems around the world.",1,ifelse(dat2$intervene=="Discouraging the US from playing an active role in solving problems around the world.",0,NA))

#armsControl: 0 oppose deproliferation, 1 support deproliferation
dat2$armsControl <- ifelse(dat2$hawk1=="Opposing an arms control treaty that would reduce both US and Russian nuclear arsenals.",0,ifelse(dat2$hawk1=="Supporting an arms control treaty that would reduce both US and Russian nuclear arsenals.",1,NA))

#milSpend: 0 decrease, 1 increase
dat2$milSpend <- ifelse(dat2$hawk2=="Decreasing military spending to allow the US to better solve international problems.",0,ifelse(dat2$hawk2=="Increasing military spending to allow the US to better solve international problems.",1,NA))

#gunControl: 0 anti, 1 pro
dat2$gunControl <- ifelse(dat2$guns=="Passing a law lowering restrictions on the sale of firearms.",0,ifelse(dat2$guns=="Passing a law making the sale of firearms more strict than they are today.",1,NA))

#taxHike: 0 anti, 1 pro
dat2$taxHike <- ifelse(dat2$tax=="Passing a new law that would lower taxes on households earning $1 million a year or more.",0,ifelse(dat2$tax=="Passing a new law that would raise taxes on households earning $1 million a year or more.",1,NA))

#abortions: 0 anti-abortion, 1 pro-choice
dat2$abortions <- ifelse(dat2$abortion=="Placing stricter limits on abortions than there are now.",0,ifelse(dat2$abortion=="Allowing abortions to be generally available to those who want it.",1,NA))

#immig: 0 reduce immigrants, 1 increase immigrants
dat2$immig <- ifelse(dat2$immigration=="Reforming America's immigration policy by decreasing the number of immigrants to the United States.",0,ifelse(dat2$immigration=="Reforming America's immigration policy by increasing the number of immigrants to the United States.",1,NA))

#affAction: 0 oppose affirmative action, 1 support affirmative action
dat2$affAction <- ifelse(dat2$affirmativeaction=="Opposing affirmative action programs designed to increase the number of racial minorities in colleges and universities.",0,ifelse(dat2$affirmativeaction=="Supporting affirmative action programs designed to increase the number of racial minorities in colleges and universities.",1,NA))

#Convert policy preference variables to numeric
loc.a <- which(colnames(dat2)=="Q157")
loc.b <- which(colnames(dat2)=="Q183")
for (i in loc.a:loc.b){
	dat2[,i] <- as.numeric(as.factor(dat2[,i]))
}

#Convert stereotype variables to numeric
loc.a <- which(colnames(dat2)=="Q183.1")
loc.b <- which(colnames(dat2)=="Q182")
for (i in loc.a:loc.b){
	temp <- rep(NA, nrow(dat2))
	temp[which(dat2[,i]=="Definitely Democratic leaders")] <- 1
	temp[which(dat2[,i]=="Probably Democratic leaders")] <- 2
	temp[which(dat2[,i]=="Probably Republican leaders")] <- 3
	temp[which(dat2[,i]=="Definitely Republican leaders")] <- 4
	temp[which(dat2[,i]=="Both Democrats and Republicans")] <- 5
	temp[which(dat2[,i]=="Neither Democrats nor Republicans")] <- 6	
	dat2[,i] <- temp
}


#Now, generate weights - will require exporting to Stata
# i <- match(c("ID", "male", "age_1", "age_2", "age_3", "age_4", "educ_1", "educ_2", "educ_3", "educ_4", "white", "pid3"), colnames(dat2))
# dat2w <- dat2[,i]
# dat2w$Dem <- recode(dat2w$pid3, binarize=TRUE, x=1)
# dat2w$Rep <- recode(dat2w$pid3, binarize=TRUE, x=3)
# write_dta(dat2w, path="Study 2 Weight Info.dta", version=13)

#Stata code (note that you'll need to set the file path)
#use "PATH/Study 2 Weight Info.dta"
#ebalance male age_2 age_3 age_4 educ_2 educ_3 educ_4 white Dem Rep, manualtargets(0.482, 0.357, 0.400, 0.182, 0.261, 0.406, 0.132, 0.702, 0.472, 0.373)
#saveold "PATH/Study 2 Weights.dta", version(13)

#Load weights
dat2w <- read_dta(file="Study 2 Weights.dta")[,c(1,15)]

#Merge weights into dataset
dat2 <- merge(dat2, dat2w, by="ID") 

#Rename weight variable
colnames(dat2)[ncol(dat2)] <- "weight"
